package com.lin.springdataredisquickstart.utils;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.annotation.Resource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

@Component
public class RedisSerializerUtil {
    @Resource
    private StringRedisTemplate stringRedisTemplate;
    private final ObjectMapper mapper = new ObjectMapper();

    /**
     * 将对象序列化成json串
     * @param key key
     * @param obj value
     */
    public <T> void set(String key, T obj) throws JsonProcessingException {
        String s = mapper.writeValueAsString(obj);
        stringRedisTemplate.opsForValue().set(key, s);
    }

    /**
     * 将json串反序列化成对象
     * @param key key
     * @param clazz 对象类字节码
     * @return 对象
     */
    public <T> T get(String key, Class<T> clazz) throws JsonProcessingException {
        String s = stringRedisTemplate.opsForValue().get(key);
        return mapper.readValue(s, clazz);
    }

    /**
     * 删除key
     * @param key key
     */
    public void delete(String... key) {
        for (String s : key) {
            stringRedisTemplate.delete(s);
        }
    }

}
